document.getElementById('login-form').addEventListener('submit', function(event) {
    event.preventDefault(); // 阻止表单默认提交行为

    // 获取用户名和密码
    const username = document.getElementById('username').value.trim();
    const password = document.getElementById('password').value.trim();

    if (!username || !password) {
        showError('用户名和密码不能为空！');
        return;
    }

    // 调用后端登录接口
    fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password }),
        credentials: 'include'
    })
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error('登录失败');
            }
        })
        .then(data => {
            if (data.status === 'success') {
                window.location.href = '/index.html'
            } else {
                showError(data.message || '用户名或密码错误！');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showError('登录失败，请稍后再试！');
        });
});

// 显示错误信息
function showError(message) {
    const errorMessageElement = document.getElementById('error-message');
    errorMessageElement.textContent = message;
}